package com.imooc.user.service.impl;

import com.imooc.api.service.BaseService;
import com.imooc.enums.Sex;
import com.imooc.enums.UserStatus;
import com.imooc.exception.GraceException;
import com.imooc.grance.result.ResponseStatusEnum;
import com.imooc.pojo.AppUser;
import com.imooc.pojo.bo.UpdateUserInfoBO;
import com.imooc.pojo.vo.AppUserInfoVO;
import com.imooc.pojo.vo.UserAccountInfoVO;
import com.imooc.user.mapper.AppUserMapper;
import com.imooc.user.service.UserService;
import com.imooc.utils.DateUtil;
import com.imooc.utils.DesensitizationUtil;
import com.imooc.utils.JsonUtils;
import com.imooc.utils.RedisOperator;
import org.apache.commons.lang3.StringUtils;
import org.n3r.idworker.Sid;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;

/**
 * Created with IntelliJ IDEA.
 *
 * @auther Levi
 * @Date: 2021/03/14/16:00
 * @Description:
 */
@Service
public class UserServiceImpl extends BaseService implements UserService {
    private static final String USER_FACE0 = "http://122.152.205.72:88/group1/M00/00/05/CpoxxFw_8_qAIlFXAAAcIhVPdSg994.png";
    private static final String USER_FACE1 = "http://122.152.205.72:88/group1/M00/00/05/CpoxxF6ZUySASMbOAABBAXhjY0Y649.png";
    private static final String USER_FACE2 = "http://122.152.205.72:88/group1/M00/00/05/CpoxxF6ZUx6ANoEMAABTntpyjOo395.png";
    public static final String REDIS_USER_INFO = "redis_user_info";

    @Autowired
    private AppUserMapper appUserMapper;
    @Autowired
    private Sid sid;
    @Autowired
    private RedisOperator redis;

    @Override
    public AppUser queryMobileIsExist(String mobile) {
        //创建一个实例对象
        Example userExample = new Example(AppUser.class);
        //创建查询条件对象
        Example.Criteria userCrit = userExample.createCriteria();
        //添加查询条件
        userCrit.andEqualTo("mobile", mobile);
        AppUser appUser = appUserMapper.selectOneByExample(userExample);
        return appUser;
    }

    @Override
    @Transactional
    public AppUser createUser(String mobile) {
        AppUser user = new AppUser();
        user.setId(sid.nextShort());
        user.setActiveStatus(UserStatus.INACTIVE.type);
        user.setBirthday(DateUtil.stringToDate("1995-8-11"));
        user.setNickname("用户"+ DesensitizationUtil.commonDisplay(mobile));
        user.setFace(USER_FACE0);
        user.setMobile(mobile);
        user.setSex(Sex.secret.type);
        user.setCreatedTime(new Date());
        user.setUpdatedTime(new Date());
        user.setTotalIncome(0);
        appUserMapper.insert(user);
        return user;
    }

    @Override
    public void updateUserInfo(UpdateUserInfoBO updateUserInfoBO) {
        String userId = updateUserInfoBO.getId();
        /**
         * 保证双写一致
         * 用户修改请求之前，为了防止redis运行异常，导致redis中的数据不同步，
         *         先把redis中的老数据给删除，然后再进行更新，更新后写入redis
         */
        redis.del(REDIS_USER_INFO+":"+userId);
        AppUser user = new AppUser();
        BeanUtils.copyProperties(updateUserInfoBO, user);
        user.setUpdatedTime(new Date());
        user.setActiveStatus(UserStatus.ACTIVE.type);
        int result = appUserMapper.updateByPrimaryKeySelective(user);
        if (result !=1) {
            GraceException.display(ResponseStatusEnum.USER_UPDATE_ERROR);
        }
        //数据更新之后，再次从数据库中查询用户信息，存入redis中，防止脏数据产生
        AppUser appUser = getUser(userId);
        redis.set(REDIS_USER_INFO+":"+userId, JsonUtils.objectToJson(appUser));
        try {
            //缓存双删策略
            Thread.sleep(100);
            redis.del(REDIS_USER_INFO+":"+userId);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    @Override
    public AppUserInfoVO getBaseUserInfo(String userId) {
        //先判断用户有没有登录
        if (StringUtils.isBlank(userId)) {
            GraceException.display(ResponseStatusEnum.UN_LOGIN);
        }
        AppUser user = appUserMapper.selectByPrimaryKey(userId);
        AppUserInfoVO userInfoVO = new AppUserInfoVO();
        BeanUtils.copyProperties(user, userInfoVO);
        String followCounts = getCountsFromRedis(REDIS_MY_FOLLOW_COUNTS + ":" + userId);
        String fansCounts = getCountsFromRedis(REDIS_WRITER_FANS_COUNTS + ":" + userId);
        userInfoVO.setMyFansCounts(fansCounts);
        userInfoVO.setMyFollowCounts(followCounts);
        return userInfoVO;
    }
    @Override
    public AppUser getUser(String userId) {
        AppUser user = appUserMapper.selectByPrimaryKey(userId);
        return user;
    }


}

